<?php
/*
 * Plugin Name: Footprint
 * Plugin URI: http://footprint.wielder.org/
 * Version: v0.2
 * Author: Javist, David
 * Description: Log down your footprint in the google map.
 * Author URI: http://www.inoct.com
 */
 
/*  Copyright YEAR  PLUGIN_AUTHOR_NAME  (email : PLUGIN AUTHOR EMAIL)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

/*
  *  insert a table to record the user's footprint information.
  */
function footprint_install() {
    global $wpdb;
    
    $table_name = $wpdb->prefix . "footprint";
    if ($wpdb->get_var ( "show tables like '$table_name'" ) != $table_name) {
        $sql = "CREATE TABLE " . $table_name . " (
                id mediumint(9) NOT NULL auto_increment,
                uid int(11) NOT NULL default '0',
                lat double NOT NULL default '0',
                lng double NOT NULL default '0',
                place varchar(255) default NULL,
                cate enum('Home','Study','Work','Tour','Birthplace','Other') NOT NULL default 'Tour',
                dt date default NULL,
                how varchar(255) default NULL,
                withwho varchar(255) default NULL,
                img_url varchar(255) default NULL,
                ref_urls text,
                description text,
                PRIMARY KEY  (id),
                UNIQUE KEY lat (lat,lng),
                KEY uid (uid),
                KEY cate (cate) );";

        require_once (ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta ( $sql );
    }
}

/*
  delete the table named footprint.
  */
function footprint_uninstall() {
  global $wpdb;
  $table_name = $wpdb->prefix . "footprint";
  $wpdb->query("DROP TABLES IF EXISTS `{$table_name}`");
}

/*
  registers a plugin function to be run when the plugin is activated. 
  insert a table named 'footprint' to record the user's marks.
 */
register_activation_hook ( __FILE__, 'footprint_install' );

/* 
 * registers a plugin function to be run when the plugin is deactivated.
 * drop the table named 'footprint'
 */
register_deactivation_hook(__FILE__, 'footprint_uninstall');

if (! class_exists ( "Footprint" )) {
    class Footprint {
        private $config;
        private $baseURL;
        private $mainJsURL;
        private $templateURL;
        private $cssURL;
        private $template;
        private $googleMapAPIURL;
        private $googleUtilLibURL = "http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js";
        
        private $adminOptionsName = "footprintAdminOptions";

        function Footprint() { //constructor
            $this->baseURL         = get_bloginfo ( 'wpurl' ) . '/wp-content/plugins/footprint/';
            $this->templateURL     = $this->baseURL . "templates/";
            $this->cssURL          = $this->baseURL . "css/";
            $this->loadConfig();
            //$this->googleMapAPIURL = "http://maps.google.com/maps?file=api&amp;v=2&amp;key=" . $this->config ['GoogleMap.APIKey'];
            $options               = get_option('footprintAdminOptions');
            $this->googleMapAPIURL = "http://maps.google.com/maps?file=api&amp;v=2&amp;key=" . $options['google_map_api_key'];
            $this->mainJsURL       = $this->baseURL . "js/footprint.js";
        }

        function processContent($content = "") {
            if ($this->containFootprint ( $content )) {
              $this->loadTemplate ();
              $content = str_replace ( "[Footprint]", $this->template, $content );
            }
            return $content;
        }

        function create() {
            $this->loadTemplate();
            echo $this->template;
        }

        function loadJs() {
            if (function_exists ( 'wp_enqueue_script' )) {
                wp_enqueue_script ( 'GoogleMap', $this->googleMapAPIURL );
                wp_enqueue_script ( 'GoogleUtil', $this->googleUtilLibURL );
                wp_enqueue_script ( 'FootprintMainJs', $this->mainJsURL, array ('prototype' ) );
            }
        }
        
        /*
         set the value of options when installing the plugin.
         */
        function initOptions() {
            $this->getAdminOptions();
        }
        
        /*
         get out of the value of settings from database.
         */
        function getAdminOptions() {
            $footprintAdminOptions = array(
                'google_map_api_key' => ''
            );
            
            $footprintOptions = get_option( $this->adminOptionsName );
            
            if( !empty( $footprintOptions ) ) {
                foreach( $footprintOptions as $key => $option ) {
                    $footprintAdminOptions[$key] = $option;
                }
            }
            update_option($this->adminOptionsName, $footprintAdminOptions);
            
            return $footprintAdminOptions;
        }
        
        /*
         print out the administration page.
         */
        function printAdminPage() {
            $footprintOptions = $this->getAdminOptions();
            if(isset($_POST['updateFootprintSettings'])) {
                if(isset($_POST['footprintGoogleMapApiKey'])) {
                    $footprintOptions['google_map_api_key'] = $_POST['footprintGoogleMapApiKey'];
                }
                update_option($this->adminOptionsName, $footprintOptions);
?>

            <div class="updated"><p><strong><?php _e("Settings updated.", "footprint"); ?></strong></div>

<?php       } // end if.   the following is html of admin page:  ?>

            <div class="wrap">
              <form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
                <h2>Foot Print</h2>
                <h3>Setting your Google Map API Key here:</h3>
                <input type="text" size="100" name="footprintGoogleMapApiKey">
                  <?php _e(apply_filters('format_to_edit', $footprintOptions['google_map_api_key']), 'Footprint'); ?>
                </input>
                <div class="submit">
                  <input type="submit" name="updateFootprintSettings" value="<?php _e('Update Settings', 'Footprint'); ?>" />
                </div>
              </form>
            </div>

<?php   } //End function printAdminPage()

        private function loadConfig() {
            $this->config = parse_ini_file ( "config.ini" );
        }

        private function loadTemplate() {
            //$this->template = file_get_contents ( $this->templateURL . 'template.htm' );
            $user = wp_get_current_user();
            if ($user==null||$user->ID==''){
                $isLogin = 'false';
            } else {
                $isLogin = 'true';
            }
            $this->template = "<script>";
            $this->template .= 'var footprint = new Footprint("map",480,500,"'.$this->baseURL.'",'.$isLogin.');';
            $this->template .= 'window.onunload=GUnload;';
            $this->template .= "</script>";
        }

        private function containFootprint($content = "") {
          if (substr_count ( $content, "[Footprint]" ) > 0) {
              return true;
          } else {
              return false;
          }
        }
    }
} //End Class Footprint


if (class_exists ( "Footprint" )) {
    $footprint = new Footprint ( );
}

//Initialize the admin panel
if (!function_exists("footprintAdminPanel")) {
    function footprintAdminPanel() {
        global $footprint;
        if (!isset($footprint)) {
          return;
        }
        if (function_exists('add_options_page')) {
            add_options_page('Footprint', 'Footprint', 8, basename(__FILE__), array(&$footprint, 'printAdminPage'));
        }
    }
}

if (isset ( $footprint )) {
    add_action ('admin_menu', 'footprintAdminPanel');
    add_action ( 'wp_head', array (&$footprint, 'loadJs' ), 1 );
    add_action ('footprint/footprint.php', array(&$footprint, 'initOptions'));
    add_filter ( 'the_content', array (&$footprint, 'processContent' ) );
}
?>
